package copyengine.dataLayer.query.database
{
	import copyengine.CopyEngine;
	import copyengine.utils.debug.CELog;
	import copyengine.utils.tick.GlobalTick;

	import flash.utils.getQualifiedClassName;

	import org.puremvc.as3.patterns.mediator.Mediator;

	public class CEDatabaseQueryBasic extends Mediator
	{
		protected var param:Object;

		//这里叫Source是为了实现该接口的Database可以叫 localDatabase且有机会
		//进行强制类型转换
		protected var localDatabaseSource:ICEDatabase;

		private var callBackFunctionVector:Vector.<Function>;

		public function CEDatabaseQueryBasic(_name:String, _param:Object, _localDatabase:ICEDatabase)
		{
			param = _param;
			localDatabaseSource = _localDatabase;
			callBackFunctionVector = new Vector.<Function>();
			super(_name);
		}


		public final function addCallbackFunction(_f:Function):void
		{
			callBackFunctionVector.push(_f);
		}

		override final public function onRemove():void
		{
			callBackFunctionVector = null;
			localDatabaseSource = null;
			param = null;
		}

		protected final function finishDatabaseQuery():void
		{
			CopyEngine.LOG_RPC_MOUDLE && CELog.log("LocalDataBase : " + getQualifiedClassName(this) + " finished");
			GlobalTick.instance.callLaterAfterTickCount(doFinishDatabaseQuery);
		}

		private function doFinishDatabaseQuery():void
		{
			while (callBackFunctionVector.length > 0)
			{
				var callBackFunction:Function = callBackFunctionVector.pop();
				callBackFunction(getQualifiedClassName(this), getResultData());
			}
			facade.removeMediator(getMediatorName());
		}

		/**
		 * get the data from localDatabase
		 */
		protected function getResultData():Object
		{
			throw new Error("child class should override this function");
		}

	}
}
